<template>
	<el-form ref="form" :model="form" label-width="100px" v-show="estimate == false">
		<el-form-item label="文章标题">
			<el-input v-model="form.title"></el-input>
		</el-form-item>
		<el-form-item label="文章分类">
			<el-select v-model="form.nType" placeholder="请选择">
				<el-option label="军事" value="1"></el-option>
				<el-option label="娱乐" value="2"></el-option>
				<el-option label="游戏" value="3"></el-option>
				<el-option label="小说" value="4"></el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="简短描述">
			<el-input v-model="form.description" type="textarea"></el-input>
		</el-form-item>
		<el-form-item label="关键词">
			<el-input v-model="form.keywords"></el-input>
		</el-form-item>
		<el-form-item label="文章内容">
			<!-- 这里使用textarea作为富文本的简单代替 -->
			<div ref="editorElem"></div>
		</el-form-item>
	</el-form>
	<div v-show="estimate == true">
		<el-card>
			<div slot="header">
				<h1>{{title1}}</h1>
			</div>
			<div v-html="content1"></div>
		</el-card>
	</div>
	<el-form-item style="margin-left:45% ;">
		<el-button type="primary" @click="onSubmit">立即创建</el-button>
		<el-button type="primary" @click="show">查看</el-button>
		<el-button>取消</el-button>
	</el-form-item>
</template>

<script>
	import {
		ref,
		onMounted,
		onBeforeUnmount
	} from 'vue';
	import WangEditor from 'wangeditor';
	import axios from 'axios';

	export default {
		data() {
			return {
				form: {
					title: '',
					nType: '',
					description: '',
					keywords: '',
					content: '' // 这里会存储富文本编辑器的内容
				},
				id: 0,
				estimate: false,
				title1:'',
				content1:'',
				editor: null // 添加这行来保持对编辑器实例的引用
			};
		},
		methods: {
			onSubmit() {
				this.estimate = false;
				if (this.form.title.trim().length != 0) {
					axios.post('http://localhost:8080/addNew', this.form)
						.then(response => {
							this.id = response.data
						})
						.catch(error => {
							console.error(error);
						});
				}

			},
			show() {
				axios.get('http://localhost:8080/SelectNew', {
						params: {
							id: this.id
						}
					})
					.then(response => {
						this.estimate = true;
						this.title1=response.data.title;
						this.content1=response.data.content;
					})
					.catch(error => {
						console.error(error);
					});
			}
		},
		mounted() {
			this.editor = new WangEditor(this.$refs.editorElem);
			// 设置内容变化时的回调来更新form.content
			this.editor.config.onchange = (html) => {
				this.form.content = html;
			};
			this.editor.create();
		},
		beforeUnmount() {
			// 组件卸载前销毁编辑器实例
			if (this.editor) {
				this.editor.destroy();
			}
		}
	};
</script>

<style>
	/* 确保WangEditor的样式被正确加载 */
	/* @import 'wangeditor/dist/css/wangEditor.min.css'; */
</style>